﻿using BCCommon;
using BCData.TMS.RedPacket.RedPacketReceive;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.MarketingCoupon.MarketingCouponReceive;
using BCDto.TMS.RedPacket.RedPacketReceive;
using BCEntity.Common.EntityNameConst;
using BCService.Utils;
using System;
using System.Collections.Generic;

namespace BCService.TMS.RedPacket.RedPacketReceive
{
    public class RedPacketReceiveService : IRedPacketReceiveService
    {
        private readonly IRedPacketReceiveData redPacketReceiveData;
        private readonly IRedisService redisService;
        private readonly string key = string.Format("{0}", EntityNameConst.RedPacketReceiveEntity);
        public RedPacketReceiveService(
            IRedPacketReceiveData redPacketReceiveData,
            IRedisService redisService)
        {
            this.redPacketReceiveData = redPacketReceiveData;
            this.redisService = redisService;
        }

        public bool AutoGrant(long redPacketId, AutoGrantRequestDto requestDto, AdminDto admin)
        {
            //var redPacketEntity = this.redPacketData.GetSingle(redPacketId).Result;
            //if (redPacketEntity == null)
            //{
            //    throw new ArgumentException(" 获取优惠券失败 ");
            //}
            //if (requestDto.Count.HasValue && redPacketEntity.CouponCount - redPacketEntity.ReceivedCount < requestDto.Count.Value)
            //{
            //    throw new ArgumentException(" 当前优惠券数量不足,不可完全分配至 " + requestDto.Count.Value.ToString() + "人");
            //}
            //var users = new List<long>();
            //if (requestDto.UserId.HasValue)
            //{
            //    users.Add(requestDto.UserId.Value);
            //}
            //else
            //{
            //    var userEntitiess = this.userData.GetUserList(RoleType.User, AccountStatus.Using).Result.Select(P=>P.UserId).ToList();
            //    if (!userEntitiess.Any())
            //    {
            //        throw new ArgumentException(" 获取用户失败 ");
            //    }
            //    users.AddRange(userEntitiess);
            //}
            //var entities = new List<RedPacketReceiveEntity>();
            //var redPacketReceives = this.redPacketReceiveData.GetList(null, redPacketId, null).GetAwaiter().GetResult();
            //int couponNumber = 1;
            //if (redPacketReceives.Any())
            //{
            //    couponNumber = redPacketReceives.OrderByDescending(P => P.CreateTime).FirstOrDefault().CouponNumber;
            //}
            //if (requestDto.Count.HasValue)//随机分配多少个
            //{
            //    users = GetRandomUserList(users, requestDto.Count.Value);
            //}
            //if (users.Any())
            //{
            //    this.databaseContext.BeginTransaction();
            //    for (int i = 0; i < users.Count; i++)
            //    {
            //        var entity = new RedPacketReceiveEntity()
            //        {
            //            UserId = users[i],
            //            RedPacketTypeId = redPacketEntity.RedPacketTypeId,
            //            CouponType = redPacketEntity.CouponType,
            //            RedPacketId = redPacketEntity.RedPacketId,
            //            CouponNumber = couponNumber + i,
            //            CouponName = redPacketEntity.CouponName,
            //            CouponSummark = redPacketEntity.CouponSummark,
            //            StartDate = redPacketEntity.StartDate,
            //            EndDate = redPacketEntity.EndDate,
            //            AllAmount = redPacketEntity.AllAmount,
            //            CouponAmount = redPacketEntity.CouponAmount,
            //            ApplicablePlaceCode = redPacketEntity.ApplicablePlaceCode,
            //            CreateTime=DateTime.Now,
            //        };
            //        this.redPacketReceiveData.InsertAsync(entity).GetAwaiter().GetResult();
            //    }
            //    redPacketEntity.ReceivedCount += users.Count;
            //    redPacketEntity.UpdateTime = DateTime.Now;
            //    redPacketEntity.EditAdminId = admin.AdminId;
            //    redPacketEntity.EditAdminName = admin.FullName;
            //    this.redPacketData.UpdateAsync(redPacketEntity).GetAwaiter().GetResult();
            //    this.databaseContext.Commit();
            //}
            return true;
        }

        public IEnumerable<RedPacketReceiveDto> GetList(long? redPacketTypeId, long? redPacketId, long? userId)
        {
            string cacheKey = this.redisService.GetKey(key, redPacketTypeId, redPacketId, userId);
            var resultRedis = this.redisService.TryGet(cacheKey, () =>
            {
                var result = this.redPacketReceiveData.GetList(redPacketTypeId, redPacketId, userId).Result;
                return result.As<IEnumerable<RedPacketReceiveDto>>();
            }, TimeSpan.FromDays(1));
            return resultRedis;
        }

        public PageableList<RedPacketReceiveDto> Query(AdminDto admin,long? redPacketId, long? userId, int pageIndex, int pageSize)
        {
            var agentRecordId = admin.AgentRecord.AgentRecordId;
            string cacheKey = this.redisService.GetKey(key, agentRecordId, redPacketId, userId, pageIndex, pageSize);
            var resultRedis = this.redisService.TryGet(cacheKey, () =>
            {
                var (list, count) = this.redPacketReceiveData.Query(agentRecordId,redPacketId, userId, pageIndex, pageSize).Result;
                return new PageableList<RedPacketReceiveDto>
                {
                    Items = list.As<IEnumerable<RedPacketReceiveDto>>(),
                    Count = count,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now,
                };
            }, TimeSpan.FromDays(1));
            return resultRedis;
        }
    }
}
